iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0

除了 handle_cast 與 handle_call 之外,另一個相當常用的是 handle_info/2 這個 callback 可以接收普通的 process 訊息,像是使用 send 或是 Process.send_after/4 等將為基本或是系統類的訊息。

這邊要介紹一個在 erlang 的函式 :timer.send_interval/2

在 Elixir 的使用方式為

:timer.send_interval(time, destination, message)
# 如果 destination 為目前 process 的話可以省略

現在來幫我們的 Bank 加上利息功能

  # ...
  def init(init_balance) do
    IO.puts("開戶存了 #{init_balance} 元。")
    
    # 每一秒告訴 process 一次,該計算利息了
    :timer.send_interval(1_000, :interest)
    
    {:ok, init_balance}
  end
  # ...

並且加上 handle_info 來接收這個訊息並更新餘額

  def handle_info(:interest, balance) do
    new_balance = round(balance * 1.01)

    {:noreply, new_balance}
  end

現在啟動並檢查餘額可以看到秒利率的自由感

iex(2)> {:ok, pid} = Bank.start_link(200)
開戶存了 200 元。
{:ok, #PID<0.114.0>}
iex(3)> Bank.check_balance(pid)
檢查餘額,目前有 210 元
210
iex(4)> Bank.check_balance(pid)
檢查餘額,目前有 220 元
220
iex(5)> Bank.check_balance(pid)
檢查餘額,目前有 234 元
234

上一篇
12 Client/Server API 區分
下一篇
14 GenServer 生命循環
系列文
Elixir 多工 : Processes 與 OTP15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言